$(function() {
	var thiswinurl = window.location.href,
    operateStr = "operateStatus",
    operateIdx = thiswinurl.indexOf(operateStr),
    taskNoStr = "areaTaskId",
    taskNoIdx = thiswinurl.indexOf(taskNoStr),
    operateStatus = (operateIdx == -1) ? "" : thiswinurl.substring(operateIdx + (operateStr.length + 1), taskNoIdx - 1),
    taskNoVal = (taskNoIdx == -1) ? "" : thiswinurl.substring(taskNoIdx + (taskNoStr.length + 1));
	
	
	$.ajax({
        type: "post",
        dataType: "json",
        data: {
        	"areaTaskId": taskNoVal
        },
		url: DI.queryAreaTaskDetailInfo,
		success: function(data) {
		    if (data.retFlag == 1) {
		    	mainCtrl.areaTaskId = taskNoVal;
		    	mainCtrl.operateStatus = operateStatus;
		        mainCtrl.hqTaskId = data.data.hqTaskId;
		        mainCtrl.taskTopic = data.data.taskTopic;
		        mainCtrl.taskDate = data.data.taskDate;
		        mainCtrl.disCode = data.data.disCode;
		        mainCtrl.disName = data.data.disName;
		        mainCtrl.cateCode = data.data.cateCode;
		        mainCtrl.cateName = data.data.cateName;
		        mainCtrl.targetRate = data.data.targetRate;
		        mainCtrl.completeRate = data.data.completeRate;
		        mainCtrl.totalTargetNum = data.data.totalTargetNum;
		        mainCtrl.completeNum = data.data.completeNum;
		    } else {
		        console.log("获取数据失败了哟>>>" + data.errorMessage)
		    	}
		    },
		    error: function(err) {
		        console.log(err);
		    }
		});
	 
	var mainCtrl = avalon.define({
        $id: "mainController",
        areaTaskId: "",
        hqTaskId: "",
        taskTopic: "",
        taskDate: "",
        disCode: "",
        disName: "",
        cateCode: "",
        cateName: "",
        targetRate: "",
        completeRate: "",
        totalTargetNum: "",
        completeNum: "",
        operateStatus: "",
        importXls: function() {
            $("#popup_import").show();
            popCtrl.areaTaskId = taskNoVal;
        },
        downloadtemp: function() {
            window.location.href = DI.exportAreaTaskDistInfo+"?areaTaskId="+taskNoVal;
        },
        distributionInfo: function(operateStatus, modelId, targetNum) {
            $("#popup_distribution").show();
            $("#load-assign").show();
            popCtrl.assignList = [];
            popCtrl.searchcode = "";
            $(".search-code .err-box").hide();
            location.hash = "popup_distribution";
            popCtrl.alldestnum = targetNum;
            popCtrl.areaTaskId = taskNoVal;
            popCtrl.modelId = modelId;
            popCtrl.operateStatus = operateStatus;
            $.ajax({
                type: "post",
                dataType: "json",
                data: {
                    "areaTaskId": taskNoVal,
                    "modelId": modelId
                },
                url: DI.queryAreaTaskDistributeDetail,
                success: function(data) {
                    $("#load-assign").hide();
                    if (data.retFlag == 1) {
                        popCtrl.assignList = data.data;
                        var total = 0;
                        for (var i = 0; i < popCtrl.assignList.length; i++) {
                            var iptVal = popCtrl.assignList[i].targetNum == undefined ? 0 : popCtrl.assignList[i].targetNum;
                            total += parseInt(iptVal == "" ? 0 : iptVal, 10);
                        }
                        popCtrl.curdestnum = total;
                    } else {
                        console.log("获取分配详情接口，返回数据错误")
                    }
                },
                error: function(err) {
                    $("#load-assign").hide();
                    console.log(err);
                }
            });
        },
        checkNum: function() {
            $(this).removeClass("err-ipt").removeAttr("title");;
            var reg = /^[0-9]+$/;
            if (!reg.test($(this).val())) {
                $(this).addClass("err-ipt").attr("title", "目标台数应为正整数");
            }
        }
    });
	
	var taskTable = null;
    var opts = {
        targetId: "taskTable",
        templateId: "tabletask",
        settings: {
            searchParam: {
                "areaTaskId": taskNoVal
            },
            url: DI.queryAreaTaskModelDetail,
            ajaxType: "json",
            sourceInterface: {
				INum: "totalSize",
				IData: "records"
            },
            paginationIndexName: {
                "peerpageRows": "pageSize",
                "currentPage": "pageNo"
            }
        }
    };
    
    taskTable = SwiftUI.swiftTable.getInstance(opts);
    
    var popCtrl = avalon.define({
        $id: "popController",
        assignList: [],
        searchcode: "",
        
        areaTaskId: "",
        modelId: "",
        
        //总目标数量
        alldestnum: 0,
        
        //已分配数量
        curdestnum: 0,
        operateStatus: "",
        uploadFile: function() {
            if ($("#upladFile").val() == "") {
                return;
            }
            $("#load-import").show();
            $("#form_file").ajaxSubmit({
                type: "post",
                dataType: "json",
                url: DI.importStoreDistributeInfo,
                success: function(data) {
                    $("#load-import").hide();
                    if (data.retFlag == 1) {
                        $("#popup_import").hide();
                        taskTable.searchParam.pageNo = "1";
                        taskTable.refresh();
                        PLATFORM.showTips("success", "导入成功");
                    } else {
                        PLATFORM.showTips("error", data.errorMessage);
                    }
                    $("#upladFile").after($("#upladFile").clone().val(""));
                    $("#upladFile").remove();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    console.log("ajax error");
                    console.log(XMLHttpRequest);
                }
            });
        },
        fastSearch: function() {
            var codeList = $("#popup_distribution tbody tr .region-code");
            $(".region-code.highlight").removeClass("highlight");
            $(".search-code .err-box").hide();
            if(popCtrl.searchcode.length != 4){
                $(".search-code .err-box").show();
                return;
            }
            var hashId = "";
            for (var i = 0; i < popCtrl.assignList.length; i++) {
                if (popCtrl.assignList[i].storeCode.indexOf(popCtrl.searchcode) != -1) {
                    $(codeList[i]).addClass("highlight");
                    if (hashId == "") {
                        hashId = "td_" + popCtrl.assignList[i].storeCode;
                    }
                }
            }
            location.hash = "";
            location.hash = hashId;
        },
        checkNum: function() {
            $(this).removeClass("err-ipt").removeAttr("title");
            var reg = /^[0-9]+$/;
            
            if ($(this).val() == "") {
                var total = 0;
                var iptList = $("#popup_distribution tbody .edit-ipt input");
                for (var i = 0; i < iptList.length; i++) {
                    var iptVal = $(iptList[i]).val() == "" ? 0 : $(iptList[i]).val();
                    if (!reg.test(iptVal)) {
                        popCtrl.curdestnum = '数据错误';
                        return;
                    }
                    total += parseInt(iptVal, 10);
                }
                popCtrl.curdestnum = total;
                return;
            }
           
            if (!reg.test($(this).val())) {
                $(this).addClass("err-ipt").attr("title", "目标台数应为正整数");
                popCtrl.curdestnum = '数据错误';
            } else {
                var total = 0;
                var iptList = $("#popup_distribution tbody .edit-ipt input");
                for (var i = 0; i < iptList.length; i++) {
                    var iptVal = $(iptList[i]).val() == "" ? 0 : $(iptList[i]).val();
                    if (!reg.test(iptVal)) {
                        popCtrl.curdestnum = '数据错误';
                        return;
                    }
                    total += parseInt(iptVal, 10);
                }
                popCtrl.curdestnum = total;
            }
        },
        saveRegionComm: function() {
            if ($("#popup_distribution .u-ipt.err-ipt").length > 0) {
                return;
            }
            
            var total = 0;
            var iptList = $("#popup_distribution tbody .edit-ipt input");
            for (var i = 0; i < iptList.length; i++) {
                var iptVal = $(iptList[i]).val() == "" ? 0 : $(iptList[i]).val();
                total += parseInt(iptVal, 10);
            }
            if(total < popCtrl.alldestnum){
            	PLATFORM.showTips("error", "分配数量少于总目标数量");
            	return;
            }
            
            var commData = [];
            var iptList = $("#popup_distribution tbody .edit-ipt input");
            for (var i = 0; i < iptList.length; i++) {
                var commObj = {
                    "storeTaskId": popCtrl.assignList[i].storeTaskId,
                    "modelId": popCtrl.assignList[i].modelId,
                    "storeCode": popCtrl.assignList[i].storeCode,
                    "storeName": popCtrl.assignList[i].storeCode,
                    //用-1表示删除
                    "targetNum": ($(iptList[i]).val() == "" ? -1 : $(iptList[i]).val())
                };
                commData.push(commObj);
            }
            var stringComm = JSON.stringify(commData);
            
            $("#load-assign").show();
            $.ajax({
                type: "post",
                dataType: "json",
                data: {
                    "areaTaskId": taskNoVal,
                    "distInfoJson": stringComm
                },
                url: DI.page2DistributeStoreNum,
                success: function(data) {
                	$("#load-assign").hide();
                    if (data.retFlag == 1) {
                        $("#popup_distribution").hide();
                        PLATFORM.showTips("success", "门店目标台数保存成功");
                    } else {
                        PLATFORM.showTips("error", data.errorMessage);
                    }
                },
                error: function(err) {
                	$("#load-assign").hide();
                    console.log(err);
                }
            });
        },
        refresh: function(){
        	 var searchParam = {
                     "areaTaskId": taskNoVal
                 }
        	taskTable.search(searchParam);
        }
    });
});


/*
 * firefox下回车事件不兼容问题
 * 
 */
function fastSearch(evt){
    evt = (evt) ? evt : ((window.event) ? window.event : "");  //兼容IE和Firefox获得keyBoardEvent对象
    var keyVal = evt.keyCode?evt.keyCode:evt.which;
    //$(".search-code .u-ipt").val($(".search-code .u-ipt").val().replace(/\D/g,''));
    var searchCode = $(".search-code .u-ipt").val();
    if(keyVal == 13){
        var codeList = $("#popup_distribution tbody tr .region-code");
        $(".region-code.highlight").removeClass("highlight");
        $(".search-code .err-box").hide();
        if(searchCode.length != 4){
            $(".search-code .err-box").show();
            return;
        }
        var hashId = "";
        var tableList = $("#popup_distribution tbody tr"),
            tableLen = tableList.length;
        for (var i = 0; i < tableLen; i++) {
            var curCodeObj = $(tableList[i]).find(".region-code"),
                curCode = curCodeObj.text();
            console.log(curCode);
            if (curCode.indexOf(searchCode) != -1) {
                curCodeObj.find("span").addClass("highlight");
                if (hashId == "") {
                    hashId = "td_" + curCode;
                }
            }
        }
        location.hash = "";
        location.hash = hashId;
    }
}